<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-button type="primary" @click="handleNewtask()">新建数据集</el-button>
        <el-input v-model="input" placeholder="请输入内容" class="search"><el-button slot="append" icon="el-icon-search"></el-button></el-input>
      </el-col>
    </el-row>
    <el-table
      :key="2"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="名称" prop="Name" align="center" />
      <el-table-column label="类别" prop="Class" align="center" />
      <el-table-column label="来源" prop="From" align="center" />
      <el-table-column label="数量" width="100" prop="Count" align="center" />
      <el-table-column label="状态" width="150" prop="Status" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.Status | statusFilter">
            <i :class="row.Status | statusIconFilter" />
            {{ row.Status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="CreateTime" align="center" width="200" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button-group>
            <el-button type="primary" size="mini" title="查看" @click="handleVideoList(row)">查看</el-button>
            <el-button type="danger" size="mini" title="删除">删除</el-button>
            <el-button type="success" size="mini" title="上传" @click="handleUpload(row)">上传</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.Page" :limit.sync="listQuery.Size" style="text-align:right" @pagination="getList" />
    </el-row>

    <el-dialog title="新建数据集" :visible.sync="dialogNewtask" width="60%">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="名称">
          <el-input v-model="temp.DataSetName" />
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="temp.FileType">
            <el-radio :label="0">视频</el-radio>
            <el-radio :label="1">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="来源">
          <el-input v-model="temp.From" />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="temp.Class" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNewtask = false">取消</el-button>
        <el-button type="primary" @click="createData()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="数据详情" :visible.sync="dialogVisible" width="80%">
      <el-table
        :key="tableKey"
        v-loading="listInfoLoading"
        :data="listInfo"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="序号" prop="Id" align="center" />
        <el-table-column label="文件名" prop="Name" min-width="150px" align="center" />
        <el-table-column label="文件大小" prop="Size" align="center" />
        <el-table-column label="格式" prop="Format" align="center" />
      </el-table>
      <pagination v-show="totalInfo>0" :total="totalInfo" :page.sync="listInfoQuery.Page" :limit.sync="listInfoQuery.Size" style="text-align:right" @pagination="handleVideoList" />
    </el-dialog>
    <el-dialog title="上传文件" :visible.sync="dialogUpload" width="60%">
      <uploader
        @complete="successUpload"
        :options="uploadOptions"
        class="uploader-example">
        <uploader-unsupport></uploader-unsupport>
        <uploader-drop style="margin:0 auto;width:500px;height:300px;">
          <P>Drop files here to upload or</P>
          <!-- <uploader-btn ref="selectVideo" v-if="DataSetType===0" :attrs="attrsVideo">select videos</uploader-btn>
          <uploader-btn ref="selectImage" v-else :attrs="attrsImage">select images</uploader-btn>
          <uploader-btn :directory="true">select folder</uploader-btn> -->

          <!-- 上传 -->
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <div style="margin-left:80px;margin-top:80px; " >
            <el-button style="width:120px;height:40px;" type="primary" @click="upload()">确认</el-button>
            <el-button style="width:120px;height:40px;margin-left:20px;">取消</el-button>
          </div>
         
        </uploader-drop>
        <uploader-list></uploader-list>
      </uploader>
    </el-dialog>
  </div>
</template>

<script>
import { fetchGetDataSetList, fetchGetDataSetInfo, DeleteDataSet } from '@/api/video'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import axios from 'axios'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'info',
        2: 'danger'
      }
      return statusMap[status]
    },
    statusIconFilter(status) {
      const statusMap = {
        '0': 'el-icon-check',
        '1': 'el-icon-close'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        0: '启用中',
        1: '未启用',
        2: '服务异常'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      dialogNewtask: false,
      input: '',
      uploadSuccess: false,
      updataProgress: 0,
      updataLoading: false,
      uploadFiles: {},
      DataSetType: 0,
      uploadOptions: {
        target: '/upload',
        fileParameterName: 'File',
        chunkSize: 10 * 1024 * 1024 * 1024,
        query: {
          DataSetId: -1
        },
        testChunks: false,
        parseTimeRemaining: function(timeRemaining, parsedTimeRemaining) {
          return parsedTimeRemaining
            .replace(/\syears?/, '年')
            .replace(/\sdays?/, '天')
            .replace(/\shours?/, '小时')
            .replace(/\sminutes?/, '分钟')
            .replace(/\sseconds?/, '秒')
        },
        categoryMap: {
          image: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'],
          video: ['mp4', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
          audio: ['mp3', 'wav', 'wma', 'ogg', 'aac', 'flac'],
          document: ['doc', 'txt', 'docx', 'pages', 'epub', 'pdf', 'numbers', 'csv', 'xls', 'xlsx', 'keynote', 'ppt', 'pptx']
        }
      },
      attrsVideo: {
        accept: 'video/*'
      },
      attrsImage: {
        accept: 'image/*'
      },
      temp: {
        From: '',
        DataSetName: '',
        Class: '',
        FileType: 0
      },
      rules: {
        DataSetName: [{ required: true, message: '请输入数据集名称', trigger: 'blur' }],
        Class: [{ required: true, message: '请输入数据集分类', trigger: 'blur' }],
        FileType: [{ required: true, message: '请选择数据集类型', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogVisible: false,
      dialogUpload: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        Page: 1,
        Size: 10,
        SdkId: -1
      },
      listInfo: null,
      totalInfo: 0,
      listInfoLoading: false,
      listInfoQuery: {
        Page: 1,
        Size: 10
      },
      infoId: '',

       fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}] 
    }
  },
  computed: {
    ...mapGetters(['ProjectId', 'name']),
    watchProjectId() {
      return this.$store.state.constants.ProjectId
    }
  },
  watch: {
    // watchProjectId(curVal, oldVal) {
    //   this.getList()
    // }
  },
  created() {
    const query = this.$route.query
    if (query && query.page) {
      this.listQuery.Page = query.page
      this.getList()
    } else {
      this.getList()
    }
  },
  methods: {
    successUpload() {
    },
    getList() {
      this.listLoading = true
      fetchGetDataSetList(this.listQuery).then(response => {
        this.list = response.Data
        this.total = response.Count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.Page = 1
      this.getList()
    },
    handleNewtask() {
      this.dialogNewtask = true
      this.temp = {
        From: '',
        DataSetName: '',
        Class: '',
        FileType: 0
      }
    },
    createData() {
      var params = new FormData()
      params.append('From', this.temp.From)
      params.append('DataSetName', this.temp.DataSetName)
      params.append('Class', this.temp.Class)
      params.append('FileType', this.temp.FileType)
      console.log(params.get('From'))
      this.$axio
      axios.post('/VideoServer/CreateDataSet', params).then(response => {
        this.dialogNewtask = false
        this.getList()
      })
    },
    handleVideoList(row) {
      if (row.Id) {
        this.infoId = row.Id
      }
      this.dialogVisible = true
      this.listInfoLoading = true
      const params = {
        ...this.listInfoQuery,
        DataSetId: this.infoId
      }
      fetchGetDataSetInfo(params).then(response => {
        this.listInfo = response.Data.map(item => {
          var size = item.Size / 1024 / 1024
          item.Size = size.toFixed(3) + 'MB'
          return item
        })
        this.totalInfo = response.Count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listInfoLoading = false
        }, 0.5 * 1000)
      }).catch(() => {
        this.listInfoLoading = false
      })
    },
    handleDeleteDataSet(row) {
      const params = {
        DataSetId: row.Id
      }
      DeleteDataSet(params).then(response => {
        this.$message({
          type: 'success',
          message: '成功删除!',
          duration: 1500
        })
        this.getList()
      })
    },
    handleUpload(row) {
      this.dialogUpload = true
      this.DataSetType = row.Type
      this.uploadOptions.query.DataSetId = row.Id
      this.$nextTick(() => {
        if (this.DataSetType === 0) {
          this.$refs.selectVideo.$el.children[0].accept = 'video/*'
        } else {
          this.$refs.selectImage.$el.children[0].accept = 'image/*'
        }
      })
      
    },
   /* 上传的方法*/
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    },
  /*  upload(){
      this.$alert("已上传")
    },*/
    handleCreate() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleFileChange(files, fileList) {
      if (fileList.length > 1) {
        fileList.shift()
      }
      this.FileName = fileList[0].name
    },
    handleFileUpload(option) {
      this.uploadFiles.File = option.file || null
    },

    handleSuccess() {
      this.handleFilter()
      this.updataLoading = false
      this.dialogFormVisible = false
      this.$refs.dataForm.resetFields()
      // this.uploadSuccess = true
      // if (this.updataProgress === 99) {
      //   this.updataProgress = 100
      //   setTimeout(() => {
      //     this.handleFilter()
      //     this.updataLoading = false
      //     this.dialogFormVisible = false
      //     this.$refs.dataForm.resetFields()
      //   }, 800)
      // }
    },
    handleProgress(option) {
      // console.log(option)
      // if (option.percent === 100 && this.uploadSuccess) {
      //   this.updataProgress = 100
      //   setTimeout(() => {
      //     this.handleFilter()
      //     this.updataLoading = false
      //     this.dialogFormVisible = false
      //     this.$refs.dataForm.resetFields()
      //   }, 800)
      // } else if (option.percent === 100 && !this.uploadSuccess) {
      //   this.updataProgress = 99
      // } else {
      //   this.updataProgress = Number(option.percent.toFixed(2))
      // }
    },
    handleError() {
      this.updataLoading = false
      this.dialogFormVisible = false
    }
  }
</script>

<style lang="scss" scoped>
  .app {
    &-container {
      margin: 30px;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
  .search {
    width: 30%;
    float: right;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>

